package com.example.nowcodercommunity.service;

import com.example.nowcodercommunity.dao.CommentMapper;
import com.example.nowcodercommunity.entity.Comment;
import com.example.nowcodercommunity.entity.Event;
import com.example.nowcodercommunity.event.EventProducer;
import com.example.nowcodercommunity.util.HostHolder;
import com.example.nowcodercommunity.util.SensitiveFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;

import java.util.List;

@Service
public class CommentService {

    @Autowired
    private CommentMapper mapper;

    @Autowired
    private DiscussPostService postService;

    @Autowired
    private SensitiveFilter filter;

    public List<Comment> getCommentsByEntity(int entityType,int entityId,int offset,int limit){
        return mapper.selectCommentsByEntity(entityType, entityId, offset, limit);
    }

    public Comment getCommentById(int id){
        return mapper.selectCommentById(id);
    }

    public int getCountsCommentByEntity(int entityType,int entityId){
        try{
            return mapper.selectCountCommentsByEntity(entityType,entityId);
        }catch (Exception e){
            return 0;
        }
    }

    /**
     * 增加评论功能实现
     * isolation为隔离级别
     * propagation为传播级别
     * @param comment
     * @return
     */
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    public int addComment(Comment comment){
        if(comment==null){
            throw new RuntimeException("参数不能为空！");
        }

        // 内容过滤
        comment.setContent(HtmlUtils.htmlEscape(comment.getContent()));
        comment.setContent(filter.filter(comment.getContent()));

        int rows = mapper.insertComment(comment);

        if(comment.getEntityType()==CommunityConstant.ENTITY_TYPE_POST){
            int count = getCountsCommentByEntity(CommunityConstant.ENTITY_TYPE_POST, comment.getEntityId());
            postService.updateCommentCount(comment.getEntityId(),count);
        }

        return rows;
    }
}
